<script setup lang="ts">
  import { computed, nextTick, PropType, ref, toRefs } from 'vue'
  import { OrderTotalFee } from '@/views/order/detail/components/total-fee/types'
  import ReservationTime from '@/components/pages/order/detail/dialog/reservation-time/ReservationTime.vue'
  import WaitHandle from './wait-handle/WaitHandle.vue'
  import UpdateNetwork from '@/components/pages/order/list/update-network/UpdateNetwork.vue'
  import AssignNetwork from '@/components/pages/order/list/assign-network/AssignNetwork.vue'
  import AssignCustomerService from '@/components/pages/order/list/assign-customer-service/AssignCustomerService.vue'
  import UpdateCustomerService from '@/components/pages/order/detail/dialog/update-customer-service/UpdateCustomerService.vue'
  import FinishOrder from '@/components/pages/order/list/finish-order/FinishOrder.vue'
  import CancelOrder from '@/components/pages/order/list/cancel-order/CancelOrder.vue'
  import Reminder from '@/components/pages/order/list/reminder/Reminder.vue'
  import UpdateOrderInfoModal from '@/views/order/detail/components/order-info/UpdateOrderInfoModal.vue'
  import UpdateSettleModal from './update-settle-modal/UpdateSettleModal.vue'
  import CheckFeeDrawer from '@/components/pages/order/detail/pages/body/service-fee/fee-apply-check-dialog/FeeApplyCheckDialog.vue'
  import { useGetOrderWaitHandleList } from '@/services/pages/order/useOrderDetail'
  import CheckEndOrderModal from './check-setttlement-order/CheckStatementOrder.vue'
  import OrderPushModal from './order-push-modal.vue'
  import OrderPrint from './order-print.vue'
  import '@/utils/Print'
  import AssignEngineerModal from './assign-engineer-modal.vue'

  const {
    list: orderWaitHandleList,
    getListLoading: getOrderWaitHandleListLoading,
    getList: getOrderwaitHanldeList,
  } = useGetOrderWaitHandleList()

  defineOptions({
    name: 'OrderDetailHeaderBtnGroup',
  })

  const props = defineProps({
    orderDetail: {
      type: Object as PropType<OrderDetail>,
      required: true,
    },
    orderTotalFee: {
      type: Object as PropType<OrderTotalFee>,
      required: true,
    },
    endStatus: {
      type: Boolean,
      default: () => false,
    },
    goodList: {
      type: Array as PropType<Array<OrderDetailAPIResponse.GoodListItem>>,
      required: true,
    },
  })

  const emits = defineEmits<{
    (e: 'update'): void
    (e: 'updateCostList'): void
    (e: 'updatePartList'): void
    (e: 'update-list'): void
    (e: 'end-order-finish'): void
    (e: 'updateSettle'): void
    (e: 'update-end-order-info'): void
  }>()

  const orderPushModalVisible = ref(false)
  const assignEngineerModalVisible = ref(false)
  const checkEndOrderModalVisible = ref(false)
  const orderPrintInstance = ref<InstanceType<typeof OrderPrint> | null>(null)
  const isDianJiangYuanOrderPushSuccess = computed(() => {
    if ([1, 2].includes(props.orderDetail.status)) {
      return false
    }

    if (!props.orderDetail.network) {
      return false
    }

    if (!props.orderDetail.network.includes('电匠院')) {
      return false
    }

    if (!props.orderDetail.thirdPushState) {
      return false
    }

    if (props.orderDetail.thirdPushErrorMsg) {
      return false
    }

    return true
  })
  const { orderDetail } = toRefs(props)
  const assignCustomerServiceDialogVisible = ref(false)
  const updateCustomerServiceDialogVisible = ref(false)
  const finishOrderDialogVisible = ref(false)
  const cancelDialogVisible = ref(false)
  const reminderDialogVisible = ref(false)
  const reservationTimeDialogVisible = ref(false)
  const updateOrderInfoModalVisible = ref(false)
  const updateSettlePriceModalVisible = ref(false)
  const waitHandleEventRef = ref<InstanceType<typeof WaitHandle> | null>(null)

  /**
   * 获取待处理事项方法
   */
  const getWaitHandleEventList = () => {
    if (waitHandleEventRef.value) {
      waitHandleEventRef.value.getData()
    }
  }

  const assignNetworkDialogVisible = ref(false)
  const onAssignNetworkBtnClick = () => {
    if (orderDetail.value) {
      setUserAddress()
      assignNetworkDialogVisible.value = true
    }
  }

  const updateNetworkDialogVisible = ref(false)
  const onUpdateNetworkBtnClick = () => {
    if (orderDetail.value) {
      setUserAddress()
      updateNetworkDialogVisible.value = true
    }
  }

  const setUserAddress = () => {
    if (orderDetail.value) {
      Object.assign(userAddress.value, {
        province: orderDetail.value.province,
        city: orderDetail.value.city,
        area: orderDetail.value.area,
        town: orderDetail.value.town,
        address: orderDetail.value.address,
      })
    }
  }

  /**
   * 客户地址
   * 用于传递给分派网点弹窗组件
   */
  const userAddress = ref({
    province: '',
    city: '',
    area: '',
    town: '',
    address: '',
  })

  const onAssignEngineerClick = () => {
    assignEngineerModalVisible.value = true
  }

  const onPrintClick = () => {
    nextTick(async () => {
      let title = ''
      if (orderPrintInstance.value) {
        await orderPrintInstance.value.getOrderGoodsDetailList()
        await orderPrintInstance.value.getOrderFinishInfo()
        Print('#printId', {
          onStart: function () {
            title = window.document.title
            window.document.title =
              props.orderDetail.orderNo + '-' + props.orderDetail.sendForRepairUsername
          },
          onEnd: function () {
            window.document.title = title
          },
        })
      }
    })
  }

  defineExpose({
    getWaitHandleEventList,
    getOrderwaitHanldeList,
  })
</script>

<template>
  <div>
    <div class="order_detail_header_btns">
      <h-plain-button
        v-if="
          (!props.orderDetail.thirdPushState ||
            (props.orderDetail.thirdPushState && props.orderDetail.thirdPushErrorMsg)) &&
          props.orderDetail.network &&
          props.orderDetail.network.includes('电匠院')
        "
        v-permission="'order_push'"
        @click="orderPushModalVisible = true"
      >
        工单推送
      </h-plain-button>

      <!-- <h-plain-button v-if="endStatus" @click="checkEndOrderModalVisible = true"
        >审核结单信息</h-plain-button
      > -->

      <check-fee-drawer
        v-if="orderWaitHandleList.filter((item) => item.type === 1).length"
        :work-id="orderDetail.id"
        :work-no="orderDetail.orderNo"
        @update="emits('updateCostList')"
      >
        <h-plain-button v-permission="'order_review_fee'" :loading="getOrderWaitHandleListLoading">
          审核费用信息
        </h-plain-button>
      </check-fee-drawer>

      <!-- <wait-handle
        v-if="![4, 5].includes(orderDetail.status)"
        ref="waitHandleEventRef"
        :order-id="orderDetail.id"
        :order-no="orderDetail.orderNo"
        :network="orderDetail.network || ''"
        :network-id="orderDetail.networkId"
        :emp="orderDetail.emp"
        @update="() => emits('update')"
        @update-cost-list="() => emits('updateCostList')"
        @update-part-list="() => emits('updatePartList')"
      /> -->

      <HPlainButton
        v-if="![4, 5].includes(orderDetail.status)"
        @click="updateSettlePriceModalVisible = true"
      >
        修改结算价
      </HPlainButton>

      <HPlainButton
        v-if="[1, 2, 3].includes(orderDetail.status)"
        v-permission="'order_update'"
        @click="updateOrderInfoModalVisible = true"
      >
        修改工单
      </HPlainButton>

      <HPlainButton
        v-if="!orderDetail.assignEmp && orderDetail.status !== 4"
        v-permission="'dispatch_customer'"
        @click="assignCustomerServiceDialogVisible = true"
      >
        分派客服
      </HPlainButton>

      <HPlainButton
        v-else-if="orderDetail.assignEmp && [1, 2, 3].includes(orderDetail.status)"
        v-permission="'update_dispatch_customer'"
        @click="updateCustomerServiceDialogVisible = true"
      >
        改派客服
      </HPlainButton>

      <HPlainButton
        v-if="orderDetail.status === 1"
        v-permission="'order_assignNetwork'"
        @click="onAssignNetworkBtnClick"
      >
        分派网点
      </HPlainButton>

      <template v-else-if="orderDetail.status != 4">
        <h-plain-button
          v-if="!isDianJiangYuanOrderPushSuccess"
          v-permission="'order_updateNetwork'"
          @click="onUpdateNetworkBtnClick"
        >
          改派网点
        </h-plain-button>
      </template>

      <template v-if="!(orderDetail.status === 2 && orderDetail.dispatchNetwork === 1)">
        <h-plain-button
          v-if="
            props.orderDetail.network &&
            props.orderDetail.engineerManagerEmp &&
            props.orderDetail.status === 3
          "
          v-permission="'order_dispatch_engineer'"
          @click="onAssignEngineerClick"
        >
          改派工程师
        </h-plain-button>
        <h-plain-button
          v-if="props.orderDetail.network && !props.orderDetail.engineerManagerEmp"
          v-permission="'order_dispatch_engineer'"
          @click="onAssignEngineerClick"
          @update="emits('update')"
        >
          分派工程师
        </h-plain-button>
      </template>

      <h-plain-button
        v-if="orderDetail.status === 3"
        v-permission="'order_booking'"
        @click="reservationTimeDialogVisible = true"
      >
        预约
      </h-plain-button>

      <h-plain-button
        v-if="!(orderDetail.status === 4 || orderDetail.status === 5)"
        v-permission="'order_updateFinisher'"
        type="success"
        @click="finishOrderDialogVisible = true"
      >
        完成
      </h-plain-button>

      <h-button
        v-if="!(orderDetail.status === 4 || orderDetail.status === 5)"
        v-permission="'order_cancel'"
        @click="cancelDialogVisible = true"
      >
        取消
      </h-button>

      <h-plain-button
        v-if="!(orderDetail.status === 4 || orderDetail.status === 5)"
        v-permission="'order_urging'"
        @click="reminderDialogVisible = true"
      >
        催单
      </h-plain-button>

      <h-plain-button v-permission="'order_print'" @click="onPrintClick">打印</h-plain-button>
      <!-- <el-dropdown trigger="click" @command="handleCommand">
        <HButton>
          <span>更多</span>
          <el-icon style="margin-left: 5px">
            <ArrowDown />
          </el-icon>
        </HButton>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item
              v-if="!(orderDetail.status === 4 || orderDetail.status === 5)"
              command="a"
              @click="reminderDialogVisible = true"
              >催单</el-dropdown-item
            >
            <el-dropdown-item command="b">打印</el-dropdown-item> -->

      <!-- <template v-if="props.orderDetail && ![4, 5].includes(orderDetail.status)">
              <service-process :work-id="orderDetail.id">
                <el-dropdown-item command="c">服务过程</el-dropdown-item>
              </service-process>
            </template> -->
      <!-- </el-dropdown-menu>
        </template>
      </el-dropdown> -->
    </div>

    <AssignNetwork
      v-model="assignNetworkDialogVisible"
      :is-batch="false"
      :network-id="orderDetail.networkId"
      :network="orderDetail.network"
      :selecttion="[orderDetail.id]"
      :address="userAddress"
      @update="emits('update')"
    />

    <AssignCustomerService
      v-model="assignCustomerServiceDialogVisible"
      :is-batch="false"
      :order-ids="[orderDetail.id]"
      :current-emp="orderDetail.emp"
      @update="emits('update')"
    />

    <UpdateCustomerService
      v-model="updateCustomerServiceDialogVisible"
      :order-id="orderDetail.id"
      :current-emp="orderDetail.emp || ''"
      @update="emits('update')"
    />

    <!-- 改派网点弹窗 -->
    <UpdateNetwork
      v-model="updateNetworkDialogVisible"
      :network="orderDetail.network || ''"
      :network-id="orderDetail.networkId"
      :order-id="orderDetail.id"
      :address="userAddress"
      @update="emits('update')"
    />

    <ReservationTime
      v-model="reservationTimeDialogVisible"
      :work-id="orderDetail.id"
      @update="emits('update')"
    />

    <!-- 完成工单弹窗 -->
    <FinishOrder
      v-model="finishOrderDialogVisible"
      :order-ids="[orderDetail.id]"
      :is-batch="false"
      @update="emits('update')"
    />

    <!-- 取消工单弹窗 -->
    <CancelOrder
      v-model="cancelDialogVisible"
      :is-batch="false"
      :order-ids="[orderDetail.id]"
      @update="emits('update')"
    />

    <!-- 催单弹窗 -->
    <Reminder
      v-model="reminderDialogVisible"
      :order-ids="[orderDetail.id]"
      @update="emits('update')"
    />

    <!-- 更新工单信息弹窗 -->
    <update-order-info-modal
      v-model:visible="updateOrderInfoModalVisible"
      :order-id="orderDetail.id"
      @update="emits('update')"
    />

    <!-- 修改结算价 -->
    <update-settle-modal
      v-model="updateSettlePriceModalVisible"
      :price-form="{
        id: orderDetail.id,
        orderSettlePrice: orderTotalFee?.networkFeeSettlement?.orderSettlementPrice,
      }"
      @update="emits('updateSettle')"
    />

    <!-- 审核结单弹窗 -->
    <check-end-order-modal
      v-model="checkEndOrderModalVisible"
      :word-no="orderDetail.orderNo"
      :word-id="orderDetail.id"
      @update="emits('end-order-finish')"
    />

    <order-push-modal
      v-model="orderPushModalVisible"
      :order-id="props.orderDetail.id"
      @update="emits('update')"
    />

    <div>
      <div style="display: none">
        <order-print id="printId" ref="orderPrintInstance" :order-detail="props.orderDetail" />
      </div>
    </div>

    <assign-engineer-modal
      v-model="assignEngineerModalVisible"
      :order-detail="props.orderDetail"
      @update="emits('update')"
    />
  </div>
</template>

<style scoped lang="scss">
  .order_detail_header_btns {
    display: flex;
    gap: 5px;
  }
</style>
